//
//  BSBluetoothViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/4/8.
//  Copyright © 2016年 Ym. All rights reserved.
// identifier = 576708AC-FDB7-65BA-75B3-BB4B4D039260

#import "BSUIView.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BSBluetoothViewController.h"
/*
 1. 建立中心角色
 2. 扫描外设（discover）
 3. 连接外设(connect)
 4. 扫描外设中的服务和特征(discover)
  - 4.1 获取外设的services
  - 4.2 获取外设的Characteristics,获取Characteristics的值，获取Characteristics的Descriptor和Descriptor的值
 5. 与外设做数据交互(explore and interact)
 6. 订阅Characteristic的通知
 7. 断开连接(disconnect)
 */
@interface BSBluetoothViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

//设置一个数组的属性 存储发现的设备
//
////设置一个中心管理者
//@property (nonatomic, strong) CBCentralManager *manager;
//
//// 创建一个tableView 来展示数据
////搜到的外设
//@property (nonatomic, strong) CBPeripheral *perpheral;
////外设的特征
//@property (nonatomic, strong) CBCharacteristic *charactertic;
////信号强度
//@property (nonatomic, strong) NSNumber *RSSIValue;
//
////存储数据的路径
@property (nonatomic, strong) NSString *dataSourcePath;
//
//@property (nonatomic, strong) NSMutableArray *dataArr;
//
//@property (nonatomic, strong) NSFileHandle *fileHandle;

//校验密码提示框
@property (nonatomic, strong) BSUIView *checkBtPwView;
@property (nonatomic, strong) UITextField *bluetTextFeild;

@property (nonatomic, weak)  NSTimer *timerSearch;
@property (nonatomic , strong)BSBluetoothSingleton *bluetoothHandle;
@end

@implementation BSBluetoothViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.bluetoothHandle = [BSBluetoothSingleton shareBlutooth] ;

    self.bluetoothHandle.bsblueVC = self;//对应 不然 刷新的对象不一样
    self.navigationItem.title = @"连接蓝牙";
//    self.dataArr = [NSMutableArray array];
    [self addNavigationButton];
    [self addTableview];
    
    
    
    
//    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(readContent) userInfo:nil repeats:YES];
    
}
- (NSMutableArray *)peripherals{

    if (!_peripherals) {
        _peripherals = [[NSMutableArray alloc]init];
    }
    return _peripherals;
}


- (void)addNavigationButton{
    //   界面设计
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc]initWithTitle:@"扫描蓝牙" style:(UIBarButtonItemStylePlain) target:self action:@selector(OpenOrClose)];
    self.navigationItem.rightBarButtonItem = button1;
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(getBack)];
    self.navigationItem.leftBarButtonItem = button2;

}

//    tableview
- (void)addTableview{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:(UITableViewStyleGrouped)];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.view addSubview:_tableview];
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    
//    return 1;
//    
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"刷新时的蓝牙数目 %ld",(unsigned long)self.bluetoothHandle.peripherals.count);
    return self.bluetoothHandle.peripherals.count;
    //    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell_id";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    //    展示获取设备的名称
    CBPeripheral *peripheral = self.bluetoothHandle.peripherals[indexPath.row];
    NSString *UUIDString = [NSString stringWithFormat:@"%@",peripheral.identifier];
    NSString *subUUID = [UUIDString substringWithRange:NSMakeRange([UUIDString length]-22, 4)];
   NSString *number = [self convertStringToInt:subUUID];
    
   NSString * peripheralsName = [NSString stringWithFormat:@"BC%@",number];

    if (peripheral.name != nil) {
         cell.textLabel.text = peripheralsName;
    }
    
    return cell;
}

#pragma mark tableview的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
#pragma mark 校验密码
    UITableViewCell *cell = (UITableViewCell *) [tableView cellForRowAtIndexPath:indexPath];
    
    _bluetoothName = cell.textLabel.text;
    
    [self checkoutBluetoothPassword:indexPath.row];
    

    

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -- Go 开始找蓝牙


#pragma mark 打开蓝牙
//  开启蓝牙
- (void)OpenOrClose{
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"扫描蓝牙"]) {
        NSLog(@"扫描");
        self.navigationItem.rightBarButtonItem.title = @"断开蓝牙" ;
        
        //        1. 创建中心设备
        [self.bluetoothHandle findBluetooth];
        
#pragma mark  用定时器检测是不是找到了蓝牙设备
        
        [self performSelector:@selector(BLUSearch) withObject:nil afterDelay:10];
      //  _timerSearch = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(BLUSearch) userInfo:nil repeats:NO];
        
        
                
    }else{
        
        NSLog(@"断开");

        
        if (self.bluetoothHandle.perpheral != nil) {
            NSLog(@"didConnect start");
            [self.bluetoothHandle.manager cancelPeripheralConnection:self.bluetoothHandle.perpheral];
            
        }
        [self.peripherals removeAllObjects];
        [_bluetoothHandle.peripherals removeAllObjects];
        //停止扫描
        [self.bluetoothHandle.manager stopScan];
        //[self.bluetoothHandle.peripherals removeAllObjects];
        [self.tableview reloadData];
        self.navigationItem.rightBarButtonItem.title = @"扫描蓝牙";
    }
    
}
- (void)BLUSearch{

    if ( self.bluetoothHandle.peripherals.count == 0) {
        {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"重新扫描" message:@"未扫描到设备,请重新扫描" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                ;
            }];
            UIAlertAction *setAcion = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                [self OpenOrClose];
                
            }];
            
            [alert addAction:cancleAction];
            [alert addAction:setAcion];
            
            [self presentViewController:alert animated:YES completion:^{
                nil;
            }];
        }
    }


}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// 导航栏 隐藏
- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = YES;
}
- (void)getBack{
    

    [self.navigationController popViewControllerAnimated:YES];
    
}
//   将16进制的字符串 转为10进制的数
- (NSString *)convertStringToInt:(NSString* )hexString {
    NSString *str = @"";
    
    //  长度 - 1  因为最后一个字符是 '>' 不要的
    for(int i = 0;i < [hexString length];i ++)
        
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        
        //        碰到空格 置为空
        if (hex_char1 == ' ') {
            hex_char1 = [hexString characterAtIndex:1 + i];
            //            NSLog(@"碰到一个空格");
            i++;
        }
        
        int int_ch1;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48);   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55); //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87); //// a 的Ascll - 97
        
        if (int_ch1 > 9) {
             str = [NSString stringWithFormat:@"%@%d",str,int_ch1];
        } else {
             str = [NSString stringWithFormat:@"%@0%d",str,int_ch1];
        }
    }
    return str;
}

#pragma mark 校验密码提示框
- (void)checkoutBluetoothPassword:(NSInteger)tag{
    
    _NCview = [[UIView alloc]initWithFrame:self.view.bounds];
    _NCview.backgroundColor = BSBackViewColor;
    _NCview.alpha = 0.5;
    [self.view addSubview:_NCview];
    _checkBtPwView  = [[BSUIView alloc]initWithFrame:CGRectMake(kScrenWidth/8, kScrenHeight/2 - kMartin40, kScrenWidth*3/4, 44 *4 - 10)];
    _checkBtPwView.clipsToBounds = YES;
    _checkBtPwView.backgroundColor = BSWhite;
    _checkBtPwView.layer.cornerRadius  = 4;

    CGFloat W = _checkBtPwView.width;
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, W, 43)];
    titleLable.text = @"请输入蓝牙校验码";
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.backgroundColor = BSBackColor;
    titleLable.layer.masksToBounds = YES;
//    titleLable.layer.cornerRadius = 4;
    [_checkBtPwView addSubview:titleLable];
    
    UILabel *noteLable = [[UILabel alloc]initWithFrame:CGRectMake(0, titleLable.bottom - 4, W/3, 43 + kMartin10)];
    noteLable.text = @"  验证码:";
//    noteLable.backgroundColor = BSBackColor;
    [_checkBtPwView addSubview:noteLable];
    _bluetTextFeild = [[UITextField alloc]initWithFrame:CGRectMake(noteLable.right - 1, noteLable.top , W/3 * 2 - 1, 43 + kMartin10)];
//    _bluetTextFeild.backgroundColor = BSWhite;
    _bluetTextFeild.tag = 501;
    _bluetTextFeild.delegate = self;
    _bluetTextFeild.placeholder = @"请输入蓝牙校验码";
    
    
// 验证码下面的分割线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, noteLable.bottom, _checkBtPwView.width, 1)];
    lineView.backgroundColor = BSBackColor;
    [_checkBtPwView addSubview:lineView];
    
//    确定 和 取消   按钮
    
//    按钮的宽度
    CGFloat bw = W / 5;
    
    UIButton *confirmBT = BSButton;
    confirmBT.frame = CGRectMake(bw, lineView.bottom + kMartin15, bw + kMartin10, bw/2);
    [confirmBT setTitle:@"确定" forState:(UIControlStateNormal)];
    confirmBT.backgroundColor = BSBTGreen;
    confirmBT.tag = tag;
    [confirmBT addTarget:self action:@selector(conform:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *cancleBT = BSButton;
    cancleBT.frame = CGRectMake(W - 2 * bw, confirmBT.top,  bw + kMartin10, bw/2);
    [cancleBT setTitle:@"取消" forState:(UIControlStateNormal)];
    cancleBT.backgroundColor = BSGray;
    [cancleBT addTarget:self action:@selector(cancelS) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    confirmBT.layer.cornerRadius = 3;
    cancleBT.layer.cornerRadius = 3;
    [_checkBtPwView addSubview:confirmBT];
    [_checkBtPwView addSubview:cancleBT];
    [_checkBtPwView addSubview:_bluetTextFeild];
    
    [self.view addSubview:_checkBtPwView];
    
}
- (void)conform:(UIButton *)sender{

//    判断校验码对不对
    NSString *str = [_bluetoothName substringFromIndex:2];
    int nameVlaue = [str intValue];
    
    int checkValue = [_bluetTextFeild.text intValue];
    if (nameVlaue*4 == checkValue) {
        NSLog(@"验证码正确");
        //    点击的时候 链接 对应的蓝牙对象 第一次连接绑定设备
        NSString *user_id = [BSUserSGton userHandle].user_id;
        CBPeripheral *peripheral = self.bluetoothHandle.peripherals[sender.tag];
        [BSUserSGton userHandle].identifire = [NSString stringWithFormat:@"%@",peripheral.identifier];
        NSString *btUUID = [[BSUserSGton userHandle].identifire substringWithRange:NSMakeRange([BSUserSGton userHandle].identifire.length - 36, 36)];

        
#pragma mark        绑定设备 名字是个问题
    [PKRequestManager ChangeDeviceUserIDWithnetUrl:NetStr userID:user_id iDCode:btUUID password:@"12345678" oldpassword:_bluetTextFeild.text method:POST finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if ([dic[@"Code"] isEqualToString:@"0"]) {
            [_bluetoothHandle connectPerpheralWithIndexpathrow:sender.tag];
            
        }else{
            [PKRequestManager showAlertView:dic[@"Message"]];
        }
        NSLog(@"%@",dic);
    } error:^(NSError *error) {
        ;
    }];
        
        //    展示获取设备的名称
    }else{
        [PKRequestManager showAlertView:@"验证失败,请检查验证码"];
    }
}
- (void)cancelS{
    [_NCview removeFromSuperview];
    [_checkBtPwView removeFromSuperview];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField.tag != 506) {
        
        [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        return [self validateNumber:string];
        
    }
    return YES;
    
}
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField ) {
        
        if (textField.tag == 500) {
            if (textField.text.length > 11) {
                textField.text = [textField.text substringToIndex:11];
            }
        } else if((textField.tag == 501)) {
            if (textField.text.length > 8) {
                textField.text = [textField.text substringToIndex:8];
            }
        }
    }
}
- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)dealloc{
    
    NSLog(@"蓝牙界面销毁了");
}
@end
